package cn.yzj.common;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 生成随机码
 *
 * @author gzkemays
 * @since 2021/4/7 14:19
 */
public class VerificationCode {
  static final String BASE_NUMBER_LETTER =
      "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

  public static String builder(
      int width,
      int height,
      String codeName,
      HttpServletResponse response,
      HttpServletRequest request) {

    BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    String verifyCode = VerificationCode.randomVerification(width, height, verifyImg);
    request.getSession().setAttribute(codeName, verifyCode);
    // 获取文件输出流
    try {
      response.setContentType(ContentType.IMG_PNG);
      OutputStream os = response.getOutputStream();
      ImageIO.write(verifyImg, "png", os);
      os.flush();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return verifyCode;
  }

  public static String randomVerification(int width, int height, BufferedImage verify) {
    Graphics2D graphics2D = (Graphics2D) verify.getGraphics();
    graphics2D.setColor(Color.WHITE);
    graphics2D.fillRect(0, 0, width, height);
    graphics2D.setFont(new Font("微软雅黑", Font.BOLD, 40));
    StringBuilder sb = new StringBuilder();
    int x = 10;
    String ch = "";
    ThreadLocalRandom random = ThreadLocalRandom.current();
    for (int i = 0; i < 4; i++) {
      // 生成随机颜色
      graphics2D.setColor(getRandomColor());
      // 旋转角度小于30
      int degree = random.nextInt() % 30;
      int dot = random.nextInt(BASE_NUMBER_LETTER.length());
      ch = BASE_NUMBER_LETTER.charAt(dot) + "";
      sb.append(ch);
      // 正向旋转
      graphics2D.rotate(degree * Math.PI / 180, x, 45);
      graphics2D.drawString(ch, x, 45);
      // 反向选装
      graphics2D.rotate(-degree * Math.PI / 180, x, 45);
      x += 48;
    }
    // 画干扰线
    for (int i = 0; i < 6; i++) {
      graphics2D.setColor(getRandomColor());
      // 随机画线
      graphics2D.drawLine(
          random.nextInt(width),
          random.nextInt(height),
          random.nextInt(width),
          random.nextInt(height));
    }
    // 生成噪点
    for (int i = 0; i < 30; i++) {
      int x1 = random.nextInt(width);
      int y1 = random.nextInt(height);
      graphics2D.setColor(getRandomColor());
      graphics2D.fillRect(x1, y1, 2, 2);
    }
    return sb.toString();
  }

  /** 随机取色 */
  private static Color getRandomColor() {
    Random ran = new Random();
    return new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
  }
}
